
import sys
import time
import random
import re
import pyautogui

from Config import *
from SpiderUtil import *
from ProxyUtil import *
from RabbitUtil import RabbitUtil
from SeleniumUtil import SeleniumUtil
from SeleniumUtil import CheckDriverExit
from TimeUtil    import *

#selenium
from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
#反爬
import undetected_chromedriver as uc
#BeautifulSoup
from bs4 import BeautifulSoup

from pymysql.converters import escape_string

from ErrorCode import *

from OperUtil import *
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def OpenBeike(areaName):
    pass;


def LoginAction():
    # 判断是否需要登录

    if driver.title in '登录':
        oper.EnterInput(driver, 'input#username', Config["Spider"]["beikeAccount"])
        oper.EnterInput(driver, 'input#password', Config["Spider"]["beikePassword"])
        oper.ClickEle(driver, 'button.btn-login')

        # 获取验证码
        # 等待元素出现（最长10秒）
        wait = WebDriverWait(driver, 10)
        sms_div = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.btn-sms")))
        
        # 判断元素是否可点击
        if sms_div.is_displayed() and sms_div.is_enabled():
            sms_div.click()
            # 等待验证码
            while True:
                WarningPrompt(Type=EDetail["E210"])
                time.sleep(60)
                # 判断是否要退出
                if driver.title not in '登录':
                    break
  
        if driver.title in '登录':
            # 登录失败 告警
            WarningPrompt(Type=EDetail["E212"])
            LoginAction()
        time.sleep(10)





def AreaDetailConsumer(city, areaName):
    
    print("city=", city, "，areaName=", areaName);
    
    driver.get("https://gz.ke.com/xiaoqu/");

    # 输入小区搜索
    
    oper.EnterInput(driver, 'input#searchInput', areaName.strip())
    oper.ClickEle(driver, 'div.inputRightPart')

    LoginAction()



    # i = 1
    
    # while True:
    #     i = i + 1
    #     oper.EnterInput(driver, 'input#searchInput', areaName.strip()+ str(i))
    #     oper.ClickEle(driver, 'div.inputRightPart')
    #     time.sleep(1)

    soup = BeautifulSoup(driver.page_source, "html.parser")
    xiaoqu_num = soup.find('h2', class_='total fl').contents[1].text.strip()
    print(f"小区数量：{xiaoqu_num}")
    
    if int(xiaoqu_num) > 0:
        # 点击小区
        liArr = driver.find_elements(By.CSS_SELECTOR, 'ul.listContent li')
        if len(liArr) > 0:
            # 1. 保存原始窗口句柄
            original_window = driver.current_window_handle

            liArr[0].find_element(By.CSS_SELECTOR, 'a').click()

            time.sleep(3)

            # 3. 切换到新页面
            WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)
            for window in driver.window_handles:
                if window != original_window:
                    driver.switch_to.window(window)
                    break

            # 4. 操作新页面
            print("新页面标题:", driver.title)
            time.sleep(3)
            # 抓小区平均价
            recordLis = driver.find_elements(By.CSS_SELECTOR, 'ol.frameDealListItem li')
            if len(recordLis) > 0:
                for li in recordLis:
                    unitPrice = li.find_element(By.CSS_SELECTOR, 'div.frameDealUnitPrice').text;
                    if '元/平' in unitPrice:
                        unitPrice = float(unitPrice.replace('元/平', ''))
                    print('成交单价：', str(unitPrice));

            # 5. 关闭新页面并返回原始页面
            driver.close()
            driver.switch_to.window(original_window)


            # from selenium import webdriver
            # from selenium.webdriver.common.by import By
            # from selenium.webdriver.support.ui import WebDriverWait
            # from selenium.webdriver.support import expected_conditions as EC

            # driver = webdriver.Chrome()
            # driver.get("https://example.com")

            # # 1. 保存原始窗口句柄
            # original_window = driver.current_window_handle

            # # 2. 点击打开新页面的元素
            # driver.find_element(By.LINK_TEXT, "打开新页面").click()

            # # 3. 切换到新页面
            # WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) > 1)
            # for window in driver.window_handles:
            #     if window != original_window:
            #         driver.switch_to.window(window)
            #         break

            # # 4. 操作新页面
            # print("新页面标题:", driver.title)
            # driver.find_element(By.ID, "search_box").send_keys("test")

            # # 5. 关闭新页面并返回原始页面
            # driver.close()
            # driver.switch_to.window(original_window)



    time.sleep(6)
    

    pass;

def AreaDetailParse(proxyUrl, serverIp):
    try:

        #获得配置参数
        RabbitParam = Config["RabbitMQ"];
        #初始化Rabbit
        RabbitH = RabbitUtil(host=RabbitParam["host"], user=RabbitParam["user"], passwd=RabbitParam["passwd"], vhost=RabbitParam["vhost"]);

        time.sleep(5)


        # 测试使用
        city = '广州'
        areaName = '祈福辉煌台'
        AreaDetailConsumer(city, areaName)

        
        # 消费队列
        def BeikeAreaQueue(areaObj):
            Res = 1
            try:
                city = areaObj["city"]
                areaName = areaObj["areaObj"]
                # areaObj 小区对象，表数据信息 使用json格式吧
                Res = AreaDetailConsumer(city, areaName)
            except Exception as e:
                print("queue item except info ", e)
            return Res

        serverIp = serverIp.replace(".", "_");
        QueueName = Config["Spider"]["bkareaName"]+serverIp
        RabbitH.CreateQueues([QueueName]);
        # 从RabbitMQ中获得详情地址
        RabbitH.RegistConsumer(QueueName, BeikeAreaQueue);
        

        # RabbitH.Close();
        # SeleniumH.Quit();
        #end
    except Exception as e:
        print("queue QueueBeikeArea AreaDetailParse except info ", e)
    time.sleep(5)


# 执行详情信息获取
if __name__ == "__main__":
    ParaMap = GetSpiderParams()
    SeleniumH = SeleniumUtil(ProxyInfo=PorxyInfo(None));
    driver = SeleniumH.GetDriver();

    oper = OperUtil()
    
    while True:

        AreaDetailParse(ParaMap['proxyUrl'], ParaMap['serverIp']);
        time.sleep(10)


